package com.jd.tank;

import com.jd.tank.abstractfactory.BaseBullet;
import com.jd.tank.abstractfactory.BaseTank;

import java.awt.*;

/**
 * @program: MyTank
 * @description:
 * @author: 王术平
 * @create: 2021-01-01 15:26
 **/
public class Bullet extends BaseBullet {

    private static final int SPEED = 6;
    Rectangle rect = new Rectangle();
    private Direction dir;
    private boolean living = true;
    TankFrame tf = null;
    private Group group;

    public Bullet(int x, int y, Direction dir, Group group, TankFrame tf) {
        super(x,y);
        this.dir = dir;
        this.group = group;
        this.tf = tf;
        this.rect.x = this.x;
        this.rect.y = this.y;
        this.rect.width = WIDTH;
        this.rect.height = HEIGHT;
    }
    @Override
    public void collideWith(BaseTank tank) {
        if (this.group == tank.getGroup()) return;
        if (this.living && tank.isLiving() && this.rect.intersects(tank.getRect())) {
            tank.die();
            this.die();
        }
    }

    private void die() {
        this.living = false;
    }

    @Override
    public void paint(Graphics g) {
        if (!living) {
            tf.bullets.remove(this);
        }

        switch (dir) {
            case LEFT:
                g.drawImage(ResourceMgr.bulletL, x, y, null);
                break;
            case UP:
                g.drawImage(ResourceMgr.bulletU, x, y, null);
                break;
            case RIGHT:
                g.drawImage(ResourceMgr.bulletR, x, y, null);
                break;
            case DOWN:
                g.drawImage(ResourceMgr.bulletD, x, y, null);
                break;
        }

        move();
    }

    private void move() {
        switch (dir) {
            case LEFT:
                x -= SPEED;
                break;
            case UP:
                y -= SPEED;
                break;
            case RIGHT:
                x += SPEED;
                break;
            case DOWN:
                y += SPEED;
                break;
        }

        //update rect
        rect.x = this.x;
        rect.y = this.y;

        if (x < 0 || y < 0 || x > TankFrame.GAME_WIDTH || y > TankFrame.GAME_HEIGHT) living = false;
    }


    public Rectangle getRect() {
        return rect;
    }

    public void setRect(Rectangle rect) {
        this.rect = rect;
    }

    public Direction getDir() {
        return dir;
    }

    public void setDir(Direction dir) {
        this.dir = dir;
    }

    public boolean isLiving() {
        return living;
    }

    public void setLiving(boolean living) {
        this.living = living;
    }

    public TankFrame getTf() {
        return tf;
    }

    public void setTf(TankFrame tf) {
        this.tf = tf;
    }

    public Group getGroup() {
        return group;
    }

    public void setGroup(Group group) {
        this.group = group;
    }
}
